﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;

namespace ManYor.Phone.Common
{
    /// <summary>
    /// Web请求队列类
    /// </summary>
    public class DownloadHelper
    {
        #region -- Private --
        /// <summary>
        /// 请求队列。
        /// </summary>
        private IList<WebClient> requestQueen;
        /// <summary>
        /// 回调列表。
        /// </summary>
        private IDictionary<WebClient,RequestCompletedHandler> callbackCollection;

        #endregion

        /// <summary>
        /// 默认构造函数。
        /// </summary>
        public DownloadHelper()
        {
            requestQueen = new List<WebClient>();
            callbackCollection = new Dictionary<WebClient, RequestCompletedHandler>();
        }
        /// <summary>
        /// 当请求异常时触发事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public delegate void RequestExceptionHandler(object sender, RequestEventArgs args);
        /// <summary>
        /// 当请求正常返回时触发事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public delegate void RequestCompletedHandler(object sender, OpenReadCompletedEventArgs args);


        /// <summary>
        /// 全部的请求完成时触发该事件。
        /// </summary>
        public static event EventHandler onAllRequestCompleted;
        /// <summary>
        /// 开始请求
        /// </summary>
        public static event EventHandler onBeginRequest;
        /// <summary>
        /// 当请求异常时触发该事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static event RequestExceptionHandler onRequestException;

        /// <summary>
        /// 当请求正常返回时触发该事件,如对单独的请求设定了事件，则该事件不被触发。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public event RequestCompletedHandler onRequestCompleted;

        /// <summary>
        /// 发起请求。
        /// </summary>
        /// <param name="uri"></param>
        public void StartRequest(string uri,UriKind kind,object tag,RequestCompletedHandler callback)
        {
            WebClient client = new WebClient();
            requestQueen.Add(client);
            //记录回调
            if (callback != null)
            {
                callbackCollection.Add(client, callback);
            }
            client.OpenReadAsync(new Uri(uri, kind), tag);
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            if (onBeginRequest != null)
            {
                onBeginRequest(this, null);
            }
        }

        /// <summary>
        /// 发起请求。
        /// </summary>
        /// <param name="uri"></param>
        public void StartRequest(string uri, UriKind kind, object tag)
        {
           // System.Diagnostics.Debug.WriteLine(tag + ">");
            StartRequest(uri, UriKind.Absolute, tag, null);
        }      
        /// <summary>
        /// 发起请求,默认 UriKind:Absolute。
        /// </summary>
        /// <param name="uri"></param>
        public void StartRequest(string uri)
        {
            StartRequest(uri, UriKind.Absolute,null,null);
        }

        /// <summary>
        /// 读取数据完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            //System.Diagnostics.Debug.WriteLine(e.UserState.ToString() + "<");
            //requestQueen.Remove(sender as WebClient);
            //触发错误信息
            if (e.Error != null && onRequestException != null && e.Cancelled==false)
            {
                CancelAllRequest();
                onRequestException(sender,new RequestEventArgs(){ Error=e.Error, UserState=e.UserState});
                onAllRequestCompleted(sender, e);
            }
            //触发正常返回信息
            else 
            {
                //如果定义了回调则直接触发回调
                if (callbackCollection.ContainsKey(sender as WebClient) && callbackCollection[sender as WebClient] !=null)
                {
                    callbackCollection[sender as WebClient](sender, e);
                }
                else if (onRequestCompleted != null)
                {
                    onRequestCompleted(sender, e);
                }
                //全部请求完成
                if (requestQueen.Count == 0 && onAllRequestCompleted != null)
                    onAllRequestCompleted(sender, e);
            }
        }

        /// <summary>
        /// 当发生错误时取消所有请求
        /// </summary>
        public void CancelAllRequest()
        {
            foreach (WebClient wc in requestQueen)
            {
                wc.CancelAsync();
            }
            requestQueen.Clear();
            callbackCollection.Clear();
        }

        /// <summary>
        /// 析构函数
        /// </summary>
        ~DownloadHelper()
        {
            requestQueen.Clear();
            callbackCollection.Clear();
        }
    }


     
    /// <summary>
    /// 请求异常类
    /// </summary>
    public class RequestEventArgs:EventArgs
    {
        /// <summary>
        /// 用户请求标识
        /// </summary>
        public object UserState{get;set;}
        /// <summary>
        /// 异常信息
        /// </summary>
        public Exception Error{get;set;}
    }
}
